/**
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
** \file DataSet.cpp
** \version $Id: DataSet.cpp 25 2009-10-28 16:17:47Z rigdern $
*/

#include "DataSet.h"
#include <sstream>
#include <iostream>

database_error::database_error(const std::string& arg)
  : runtime_error(arg)
{}

void 
sqlfnGeneralizedValue(sqlite3_context *context, int huh, sqlite3_value **value)
{
  DataSet *dataSet;
  std::string attributeValue((const char *)sqlite3_value_text(value[1]));
  int attributeIndex, level;
  
  dataSet = (DataSet *)sqlite3_user_data(context);
  attributeIndex = sqlite3_value_int(value[0]);
  level = sqlite3_value_int(value[2]);
  
  try {
    dataSet->_attributes[attributeIndex]->generalizeString(attributeValue, level);
    sqlite3_result_text(context, attributeValue.c_str(), -1, SQLITE_TRANSIENT);
  } catch (std::domain_error e) {
    sqlite3_result_error(context, e.what(), -1);
  }
}

DataSet::DataSet(sqlite3* database, std::vector<BasicAttribute*> attributes)
  : _database(database),
    _attributes(attributes)
{
  int rc;

  rc = sqlite3_create_function(_database, "generalized_value", 3, SQLITE_UTF8, this, sqlfnGeneralizedValue, NULL, NULL);
  if (rc != SQLITE_OK) {
    throw database_error("Unable to create generalized_value function");
  }
  constructGeneralizationTable();
}

DataSet::~DataSet()
{}

DistanceVector DataSet::maximalVector() const
{
  std::vector<BasicAttribute*>::const_iterator it;
  DistanceVector distanceVector;
  
  for (it = _attributes.begin(); it != _attributes.end(); ++it)
    distanceVector.push_back((*it)->height());
  
  return distanceVector;
}

int
DataSet::suppressionsForGeneralization(const DistanceVector& distanceVector, unsigned int k) const
{
  std::ostringstream query;
  sqlite3_stmt *stmt;
  int i, rc, rowCount = -1;

  //query = "SELECT SUM(k) FROM (SELECT COUNT(*) AS k FROM simple GROUP BY generalized_race(race, ?), generalized_zip(zip, ?) HAVING k < ?)";
  query << "SELECT SUM(k) FROM (SELECT COUNT(*) AS k FROM generalization_table GROUP BY "
    << columnList(distanceVector) << " HAVING k < " << k << ")";
  
  rc = sqlite3_prepare_v2(_database, query.str().c_str(), -1, &stmt, NULL);
  if (rc != SQLITE_OK) {
    throw database_error(std::string("Unable to calculate suppressions: ") + sqlite3_errmsg(_database));
  }

  rowCount = 0;
  while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
    rowCount += sqlite3_column_int(stmt, 0);
  }
  if (rc != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw database_error(std::string("Unable to read suppressions: ") + sqlite3_errmsg(_database));
  }
  
  sqlite3_finalize(stmt);
  return rowCount;
}

bool
DataSet::satisfies(const DistanceVector& distanceVector, unsigned int k, unsigned int maxSup) const
{
  return suppressionsForGeneralization(distanceVector, k) <= maxSup;
}

void
DataSet::dumpGeneralizedTable(const DistanceVector& distanceVector, unsigned int k) const
{
  std::ostringstream query;
    
  query << "SELECT " << columnList(distanceVector) << " FROM generalization_table";
  dumpQueryResult(query.str().c_str());
}

void
DataSet::dumpGeneralizationTable() const
{
  dumpQueryResult("SELECT * FROM generalization_table");
}

void
DataSet::constructGeneralizationTable()
{
  int rc;
  std::ostringstream query;
  std::vector<BasicAttribute*>::const_iterator it;
  unsigned int attrIndex;
  bool printComma;
  
  rc = sqlite3_exec(_database, "DROP TABLE IF EXISTS generalization_table", NULL, 0, NULL);
  if (rc != SQLITE_OK) {
    throw database_error(std::string("Can't drop generalization table: ") + sqlite3_errmsg(_database));
  }
  
  query << "CREATE TEMPORARY TABLE generalization_table AS SELECT ";
  printComma = false;
  for (it = _attributes.begin(), attrIndex = 0; it != _attributes.end(); ++it, ++attrIndex) {
    unsigned int currentHeight, maxHeight;

    maxHeight = (*it)->height();
    for (currentHeight = 0; currentHeight <= maxHeight; ++currentHeight) {
      if (printComma)
        query << ",";
      else
        printComma = true;
      
      query << "generalized_value("
        << attrIndex << ","
        << (*it)->name() << ","
        << currentHeight
        << ") AS " << (*it)->name() << currentHeight;
    }
  }
  query << " FROM simple";
  
  rc = sqlite3_exec(_database, query.str().c_str(), NULL, 0, NULL);
  if (rc != SQLITE_OK) {
    throw database_error(std::string("Can't create generalization_table: ")
      + sqlite3_errmsg(_database));
  }
}

std::string
DataSet::columnList(DistanceVector distanceVector) const
{
  std::ostringstream columns;
  DistanceVector::const_iterator distanceVecIt;
  std::vector<BasicAttribute*>::const_iterator attrIt;
  bool printComma = false;
  
  for (distanceVecIt = distanceVector.begin(), attrIt = _attributes.begin();
    distanceVecIt != distanceVector.end() && attrIt != _attributes.end();
    ++distanceVecIt, ++attrIt)
  {
    if (printComma)
      columns << ",";
    else
      printComma = true;
    columns << (*attrIt)->name() << *distanceVecIt;
  }
  
  return columns.str();
}

void
DataSet::dumpQueryResult(const char* query) const
{
  int rc, count;
  sqlite3_stmt *stmt;
  
  rc = sqlite3_prepare_v2(_database, query, -1, &stmt, NULL);
  if (rc != SQLITE_OK) {
    throw database_error(std::string("Unable to prepare query: ")
      + sqlite3_errmsg(_database));
  }
  
  count = sqlite3_column_count(stmt);
  while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
    int i;
    for (i = 0; i < count; ++i) {
      const unsigned char *data = sqlite3_column_text(stmt, i);
      if (i != 0)
        std::cout << "\t";
      std::cout << data;
    }
    std::cout << std::endl;
  }
  if (rc != SQLITE_DONE) {
    sqlite3_finalize(stmt);
    throw database_error(std::string("Unable to read query result: ")
      + sqlite3_errmsg(_database));
  }
  
  sqlite3_finalize(stmt);
}
